import * as THREE from '../../build/three.module.js';

// 常量
const sphere = [];

// 全局变量
let mouseX = 0, mouseY = 0,
    halfX = innerWidth / 2, halfY = innerHeight / 2;

// 盒子贴图
const path = '../../textures/park3Med/';
const format = '.jpg';
const url = [
  path + 'px' + format, path + 'nx' + format,
  path + 'py' + format, path + 'ny' + format,
  path + 'pz' + format, path + 'nz' + format,
];

const cubeTexture = new THREE.CubeTextureLoader().load( url );
cubeTexture.format = THREE.RGBFormat;
cubeTexture.mapping = THREE.CubeRefractionMapping;

// 场景
const scene = new THREE.Scene();
scene.background = cubeTexture;

// 相机
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 1, 100000);
camera.position.z = 3200;

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 构建模型对象
const geo = new THREE.SphereBufferGeometry(100, 32, 16);
const mtl = new THREE.MeshBasicMaterial({ color: 0xffffff, envMap: cubeTexture, refractionRatio: 0.95 });

for(let i = 0; i < 500; i += 1) {
  const mesh = new THREE.Mesh(geo, mtl);

  mesh.position.set(
    Math.random() * 10000 - 5000,
    Math.random() * 10000 - 5000,
    Math.random() * 10000 - 5000
  )

  // mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 3 + 1;

  scene.add(mesh);

  sphere.push(mesh);
}

// 渲染函数
const render = () => {

  const time = new Date() * 0.0001;

  for(let i = 0; i < sphere.length; i += 1) {
    const mesh = sphere[i];

    mesh.position.x = 5000 * Math.sin( time + i );
    mesh.position.y = 5000 * Math.cos( time + i * 1.1 );
  }

  camera.position.x += (-mouseX - camera.position.x) * 0.05;
  camera.position.y += (mouseY - camera.position.y) * 0.05;

  camera.lookAt(scene.position);

  renderer.render(scene, camera);
}

// 驱动
const animte = () => {
  requestAnimationFrame(animte);

  render();
}
animte();

// 事件监听
const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  halfX = innerWidth / 2;
  halfY = innerHeight / 2;

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);

const handleMousemove = e => {
  mouseX = (e.clientX - halfX) * 10;
  mouseY = (e.clientY - halfY) * 10;
}
window.addEventListener('mousemove', handleMousemove, false);
